#include "include.h"
#include "func.h"
#include "func_bt.h"

void sbc_decode_exit(void);
extern u8 bsp_get_light_mode(void);

func_bt_t f_bt;
u32 key_ticks=0;
u8 long_wakeup=0;
u8 need_reconnect_flag=0;
u8 reconnect_cnt=0;
ALIGNED(64)
u16 func_bt_chkclr_warning(u16 bits)
{
    u16 value;
    GLOBAL_INT_DISABLE();
    value = f_bt.warning_status & bits;
    if(value != 0) {
        f_bt.warning_status &= ~value;
        GLOBAL_INT_RESTORE();
        return value;
    }
    GLOBAL_INT_RESTORE();
    return value;
}


#if FUNC_BT_EN
#if BT_HFP_REC_EN
void bt_sco_rec_start(void);
void bt_sco_rec_stop(void);
void bt_sco_rec_mix_do(u8 *buf, u32 samples);
void bt_sco_rec_init(void);

AT(.com_text.bt_rec)
void bt_sco_rec_mix(u8 *buf, u32 samples)
{
    bt_sco_rec_mix_do(buf, samples);
}

AT(.text.func.bt)
void func_bt_sco_rec_init(void)
{
    rec_src.spr = SPR_8000;
    rec_src.nchannel = 0x01;
    rec_src.source_start = bt_sco_rec_start;
    rec_src.source_stop  = bt_sco_rec_stop;
    f_bt.rec_pause = 0;
    rec_cb.sco_flag = 1;
    bt_sco_rec_init();
}
#endif

#if BT_REC_EN
void bt_music_rec_start(void);
void bt_music_rec_stop(void);

AT(.text.func.bt)
void bt_music_rec_init(void)
{
    rec_src.spr = SPR_44100;
    if (DAC_OUT_SPR == DAC_OUT_48K) {
        rec_src.spr = SPR_48000;
    }
#if KARAOK_REC_EN
    rec_src.nchannel = 0x11;
#else
	rec_src.nchannel = 0x82;
#endif
    rec_src.source_start = bt_music_rec_start;
    rec_src.source_stop  = bt_music_rec_stop;
    f_bt.rec_pause = 0;
    rec_cb.sco_flag = 0;
}


AT(.text.func.bt)
bool bt_rec_status_process(void)
{
    if (func_cb.sta == FUNC_BT) {
        func_bt_status();
        if ((f_bt.disp_status > BT_STA_PLAYING) || (f_bt.disp_status < BT_STA_CONNECTED)) {
            if ((f_bt.disp_status > BT_STA_PLAYING) && rec_cb.sco_flag) {
                return true;
            }
            f_bt.rec_pause = 1;
            return false;       //结束录音
        }
    }
    return true;
}

AT(.text.func.bt)
void bt_music_rec_continue(void)
{
#if !BT_HFP_REC_EN
    if ((f_bt.rec_pause) && ((f_bt.disp_status == BT_STA_PLAYING) || (f_bt.disp_status == BT_STA_CONNECTED))) {
        msg_enqueue(KU_REC);    //继续录音
        f_bt.rec_pause = 0;
    }
#endif
}

#endif // BT_REC_EN
AT(.com_text.bt_rec)
void bt_set_scan_mode(u8 dis,u8 connect)
{
	cfg_bt_scan_ctrl_mode=1;
	bt_set_scan(dis,connect);
	//cfg_bt_scan_ctrl_mode=0;
	delay_5ms(10);
}

void func_bt_mp3_res_play(u32 addr, u32 len)
{
    if (len == 0) {
        return;
    }

#if BT_TWS_EN
    bool tws_res_is_busy(void);
    while(tws_res_is_busy()) {
        tws_res_proc();
    }
#endif

#if BT_REC_EN
    sfunc_record_pause();
#endif
	amp_speaker_unmute();
    bt_audio_bypass();
    mp3_res_play(addr, len);
    bt_audio_enable();
	if(f_bt.disp_status != BT_STA_PLAYING)
	{
		amp_speaker_mute();
	}
#if BT_REC_EN
    sfunc_record_continue();
#endif
}

//切换提示音语言
void func_bt_switch_voice_lang(void)
{
#if (LANG_SELECT == LANG_EN_ZH)
    if (xcfg_cb.lang_id >= LANG_EN_ZH) {
        sys_cb.lang_id = (sys_cb.lang_id) ? 0 : 1;
        multi_lang_init(sys_cb.lang_id);
        param_lang_id_write();
        param_sync();
        if (xcfg_cb.bt_tws_en) {
            bt_tws_sync_setting();                                              //同步语言
            tws_res_play(TWS_RES_LANGUAGE_EN + sys_cb.lang_id);                 //同步播放语言提示音
        } else {
            func_mp3_res_play(RES_BUF_LANGUAGE_MP3, RES_LEN_LANGUAGE_MP3);
        }
    }
#endif
}

#if BT_TWS_EN
static void func_bt_tws_set_channel(void)
{
    if(f_bt.tws_status & 0xc0) {   //对箱状态.
        tws_get_lr_channel(f_bt.tws_status);
        dac_mono_init(0, sys_cb.tws_left_channel);
    } else {
        dac_mono_init(1, 0);
    }
}

u8 func_bt_tws_get_channel(void)
{
    return sys_cb.tws_left_channel;
}
#endif

void func_bt_warning(void)
{
    u16 tws_warning;
#if BT_TWS_EN
    bool tws_res_is_busy(void);
    while(tws_res_is_busy()) {
        tws_res_proc();
    }
#endif

    tws_warning = func_bt_chkclr_warning(BT_WARN_TWS_DISCON | BT_WARN_TWS_CON);
    if(tws_warning) {
#if BT_TWS_EN
        if(xcfg_cb.bt_tws_en) {
            if(xcfg_cb.bt_tws_lr_mode != 0) {
                func_bt_tws_set_channel();
            }
        #if WARNING_BT_TWS_DISCON
            if (tws_warning == BT_WARN_TWS_DISCON) {
                func_mp3_res_play(RES_BUF_TWS_DISCON_MP3, RES_LEN_TWS_DISCON_MP3);
            }
        #endif
        }
#endif
    }

    if(func_bt_chkclr_warning(BT_WARN_DISCON)) {
#if WARNING_BT_DISCONNECT
		sys_cb.sco_start=0;
		if(!f_bt.manu_disconnect)
		{
			bsp_set_led_mode(LED_POWER_OFF);
			//bt_set_scan(true,true);
			bt_set_scan_mode(false,true);
        	func_mp3_res_play(RES_BUF_DISCONNECT_MP3, RES_LEN_DISCONNECT_MP3);
		}
		f_bt.manu_disconnect=0;
		sys_cb.vol_sync_to_remote=0;
		f_bt.sync_vol_cnt=0;
#endif // WARNING_BT_DISCONNECT
#if WARNING_BT_WAIT_CONNECT
        func_mp3_res_play(RES_BUF_WAIT4CONN_MP3, RES_LEN_WAIT4CONN_MP3);
#endif // WARNING_BT_WAIT_CONNECT
        f_bt.autoplay = 0;
    }

	if(func_bt_chkclr_warning(BT_WARN_CON)) {
#if WARNING_BT_CONNECT
		sys_cb.vol_sync_to_remote=1;
		f_bt.sync_vol_cnt=0;

		bsp_set_led_mode(LED_BT_CONNECTED);
        func_mp3_res_play(RES_BUF_CONNECTED_MP3, RES_LEN_CONNECTED_MP3);
#endif
        f_bt.autoplay = 1;
    }

#if WARNING_BT_TWS_CONNECT && BT_TWS_EN
    if(xcfg_cb.bt_tws_en) {
        tws_warning = func_bt_chkclr_warning(BT_WARN_TWS_SCON | BT_WARN_TWS_MCON );
        if(tws_warning != 0) {
            f_bt.tws_had_pair = 1;
            if (xcfg_cb.bt_tws_lr_mode != 0) {
                func_bt_tws_set_channel();
            }
            ///固定声道方案，TWS连接后异步播放声道提示音。否则同步播放连接提示音
            if (xcfg_cb.bt_tws_lr_mode >= 8) {
                tws_get_lr_channel(tws_warning << 4);

                if(sys_cb.tws_left_channel) {
                    func_mp3_res_play(RES_BUF_LEFT_CH_MP3, RES_LEN_LEFT_CH_MP3);
                } else {
                    bt_audio_bypass();
                    delay_5ms(200);
                    func_mp3_res_play(RES_BUF_RIGHT_CH_MP3, RES_LEN_RIGHT_CH_MP3);
                    bt_audio_enable();
                }
            } else {
                if (tws_warning & BT_WARN_TWS_MCON) {
                    tws_res_play(TWS_RES_TWS_CONNECTED);
                }
            }
        }
    }
#endif
#if WARNING_BT_PAIR
    if(func_bt_chkclr_warning(BT_WARN_PAIRING)) {
        func_mp3_res_play(RES_BUF_PAIRING_MP3, RES_LEN_PAIRING_MP3);
    }
#endif
#if BT_HID_MANU_EN
    //按键手动断开HID Profile的提示音
    if (xcfg_cb.bt_hid_menu_en) {
    #if WARNING_BT_HID_MENU
        if (func_bt_chkclr_warning(BT_WARN_HID_CON)) {
            func_mp3_res_play(RES_BUF_CAMERA_ON_MP3, RES_LEN_CAMERA_ON_MP3);
        }
    #endif

    #if WARNING_BT_HID_MENU
        if (func_bt_chkclr_warning(BT_WARN_HID_DISCON)) {
            func_mp3_res_play(RES_BUF_CAMERA_OFF_MP3, RES_LEN_CAMERA_OFF_MP3);
        }
    #endif

    #if BT_HID_DISCON_DEFAULT_EN
        if (f_bt.hid_discon_flag) {
            if (bt_hid_is_ready_to_discon()) {
                f_bt.hid_discon_flag = 0;
                bt_hid_disconnect();
            }
        }
    #endif // BT_HID_DISCON_DEFAULT_EN
    }
#endif // BT_HID_MANU_EN
}


void func_bt_disp_status(void)
{
    uint status = bt_get_disp_status();
	uint tmp_status;
    if(f_bt.disp_status != status) {
		tmp_status=f_bt.disp_status;
        f_bt.disp_status = status;
        f_bt.sta_update = 1;
        if(!bt_is_connected()) {
            en_auto_pwroff();
            sys_cb.sleep_en = BT_PAIR_SLEEP_EN;
        } else {
            dis_auto_pwroff();
            sys_cb.sleep_en = 1;
        }
		printf("bt status:%d\n",f_bt.disp_status);
		if(f_bt.disp_status<BT_STA_PLAYING&&(!sys_cb.sco_start))
		{
			amp_speaker_mute();
		}
        switch (f_bt.disp_status) {
        case BT_STA_CONNECTING:
            if (BT_RECONN_LED_EN) {
                led_bt_reconnect();
                break;
            }
			break;
        case BT_STA_INITING:
        case BT_STA_IDLE:
			//bsp_set_led_mode(LED_BT_PAIR);
            led_bt_idle();
#if WARNING_BT_PAIR
            if(f_bt.need_pairing && f_bt.disp_status == BT_STA_IDLE) {
                f_bt.need_pairing = 0;
                if(xcfg_cb.warning_bt_pair && xcfg_cb.bt_tws_en) {
                    f_bt.warning_status |= BT_WARN_PAIRING;
                }
            }
#endif
            break;
        case BT_STA_SCANNING:
			//bsp_set_led_mode(LED_BT_PAIR);
            led_bt_scan();
            break;

        case BT_STA_DISCONNECTING:
            led_bt_connected();
            break;

        case BT_STA_CONNECTED:
			f_bt.bt_status=0;
			f_bt.out_f_range=0;
			f_bt.manu_disconnect=0;
            led_bt_connected();
            break;
        case BT_STA_INCOMING:
			bsp_set_led_mode(LED_BT_CALL_COMING);
            led_bt_ring();
            break;
        case BT_STA_PLAYING:
			f_bt.bt_status=0;
			//bt_reset_playing_timeout();
			amp_speaker_unmute();
			//set_timeout_time();
			//bsp_set_led_mode(LED_SEQUENCE_3);
            led_bt_play();
            break;
        case BT_STA_OUTGOING:
        case BT_STA_INCALL:
			if(f_bt.disp_status==BT_STA_INCALL)
			{
				bsp_set_led_mode(LED_POWER_ON);
			}
			else
			{
				bsp_set_led_mode(LED_BT_CALL_COMING);
			}
            led_bt_call();
            break;
        }

        if(f_bt.disp_status >= BT_STA_CONNECTED) {
            f_bt.need_pairing = 1;
        }
#if BT_BACKSTAGE_EN
        if (f_bt.disp_status < BT_STA_PLAYING && func_cb.sta_break != FUNC_NULL) {
            func_cb.sta = func_cb.sta_break;
        }
#endif
    }
}

AT(.text.func.bt)
void func_bt_status(void)
{
    func_bt_disp_status();

#if FUNC_BTHID_EN
    if(is_bthid_mode()) {
        func_bt_hid_warning();
    } else
#endif
    {
        func_bt_warning();
    }
}

AT(.text.func.bt)
void func_bt_sub_process(void)
{
    func_bt_status();
}

AT(.text.func.bt)
void func_bt_process(void)
{
    func_process();
    func_bt_sub_process();

#if USER_TKEY_DEBUG_EN
    spp_tkcnt_tx();
#endif // USER_TKEY_DEBUG_EN

    if(f_bt.disp_status == BT_STA_INCOMING) {
#if BT_HFP_RING_NUMBER_EN
        sfunc_bt_ring();
#endif
		sfunc_bt_ring();
        reset_sleep_delay();
        reset_pwroff_delay();
        f_bt.siri_kl_flag = 0;
        f_bt.user_kl_flag = 0;
#if BT_REC_EN
        bt_music_rec_continue();
#endif
    } else if(f_bt.disp_status == BT_STA_OTA) {
    #if SYS_KARAOK_EN
        bsp_karaok_exit(AUDIO_PATH_KARAOK);
    #endif
        sfunc_bt_ota();
        reset_sleep_delay();
        reset_pwroff_delay();
    } else if(f_bt.disp_status >= BT_STA_OUTGOING) {
        sfunc_bt_call();
        reset_sleep_delay();
        reset_pwroff_delay();
        f_bt.siri_kl_flag = 0;
        f_bt.user_kl_flag = 0;
#if BT_REC_EN
        bt_music_rec_continue();
#endif
    }

    if(sys_cb.pwroff_delay == 0) {
        sys_cb.pwrdwn_tone_en = 1;
        func_cb.sta = FUNC_PWROFF;
        return;
    }
    if(sleep_process(bt_is_sleep)) {
        f_bt.disp_status = 0xff;
    }
}

AT(.text.func.bt)
void func_bt_init(void)
{
    if (!f_bt.bt_is_inited) {
        msg_queue_clear();
        bsp_bt_init();
        f_bt.bt_is_inited = 1;
    }
}

AT(.text.func.bt)
void func_bt_chk_off(void)
{
    if ((func_cb.sta != FUNC_BT) && (f_bt.bt_is_inited)) {
#if BT_PWRKEY_5S_DISCOVER_EN
        bsp_bt_pwrkey5s_clr();
#endif
        bt_disconnect(1);
        bt_off();
        f_bt.bt_is_inited = 0;
    }
}
u8 bt_device_addr[6];
u8 bt_device_num;
u8 reconnect_order;
u8 rconnect_order_cnt=0;
extern u8 addr_buf[6];
AT(.text.func.bt)
void func_set_reconnect_device(void)
{
	if(bt_device_num!=2||f_bt.out_f_range)
	{
		return;
	}

	if(rconnect_order_cnt>6)
	{
		reconnect_order=!reconnect_order;
		rconnect_order_cnt=0;
		printf("......\n");
		//bt_disconnect(0);
		//reconnect_cnt=3;
		//need_reconnect_flag=2;
		//return;
	}
	printf("reconnect order:%d\n",reconnect_order);
	//bt_set_scan(false,true);
	if((reconnect_order==1)&&bt_nor_get_link_info_addr(addr_buf,reconnect_order))
	{
		//printf("bt addr: ");
		//print_r(addr_buf,6);
		bt_get_connect_addr(bt_device_addr);
    	bt_connect_address();
		rconnect_order_cnt++;

	}
	else
	{
		bt_connect(3);
		rconnect_order_cnt=7;
		//bt_connect(BT_POWER_UP_RECONNECT_TIMES);
	}

}
AT(.text.func.bt)
void func_bt_reconnect_tts(void)
{
	//bsp_set_light_mode(LIGHT_SEQUENCE_6A);
	if(f_bt.idle_cnt<(BT_RECONNNECT_TIMEOUT-10))
	{
		return;
	}
	bsp_set_led_mode(LED_BT_RECONNECT);
	printf("out_f_range 00:%d\n",f_bt.out_f_range);
	if(!f_bt.out_f_range)
	{
		//func_mp3_res_play(RES_BUF_EN_RECONNECT_MP3, RES_LEN_EN_RECONNECT_MP3);
	}
}
AT(.text.func.bt)
void func_bt_reconnect_fail_tts(void)
{
	if(f_bt.bt_status==2)
	{
		need_reconnect_flag=2;
		reconnect_cnt=0;
		func_set_reconnect_device();
	}
	else
	{
		if(!f_bt.manu_disconnect)
		{
			//bsp_set_led_mode(LED_BT_RECONNECT);
		}		
	}


	//bsp_set_led_mode(LED_SEQUENCE_10B);
	//func_mp3_res_play(RES_BUF_EN_TIMEOUT_MP3, RES_LEN_EN_TIMEOUT_MP3);
}
AT(.text.func.bt)
void func_bt_into_pair_mode(void)
{
	printf("into pair!!!\n");
	f_bt.idle_cnt=0;
	
	if(f_bt.disp_status>=BT_STA_CONNECTED)
	{
		bt_disconnect(1);
	}
	else
	{
		bt_abort_reconnect();
	}
	bt_set_scan_mode(true,true);
	f_bt.manu_disconnect=1;
	f_bt.bt_status=1;
	f_bt.out_f_range=0;
	need_reconnect_flag=0;
	reconnect_cnt=0;
	f_bt.max_timeout=BT_IDLE_TIMEOUT;
	bsp_set_led_mode(LED_BT_PAIR);
    func_mp3_res_play(RES_BUF_PAIRING_MP3, RES_LEN_PAIRING_MP3);
}
AT(.text.func.bt)
void func_bt_cancel_pair_mode(void)
{
	if(f_bt.disp_status>=BT_STA_CONNECTED)
	{
		return;
	}
	if(f_bt.bt_status==3)
	{
		return;
	}
	f_bt.bt_status=3;
	bt_set_scan_mode(false,true);
	bsp_set_led_mode(LED_BT_PAIR_FAIL);
	func_mp3_res_play(RES_BUF_EN_TIMEOUT_MP3, RES_LEN_EN_TIMEOUT_MP3);
	//reconnect_order=0;
	//bt_connect(BT_POWER_UP_RECONNECT_TIMES);	
}
AT(.text.func.bt)
void func_bt_lossconnect_msg(void)
{
	f_bt.out_f_range=1;
	f_bt.idle_cnt=0;
	f_bt.bt_status=2;
	//bt_set_scan_mode(false,true);
	bsp_set_led_mode(LED_BT_RECONNECT);
	//bt_connect(BT_TIME_OUT_RECONNECT_TIMES);
	//set_timeout_time();
}
AT(.text.func.bt)
void func_bt_reconnect_finish_msg(void)
{
	if(!f_bt.out_f_range)
	{
		return;
	}
	if(f_bt.idle_cnt<BT_OUTOFRANGE_TIMEOUT)
	{
		bt_connect(4);
	}
	else
	{
		f_bt.out_f_range=0;
		bt_abort_reconnect();
		bt_disconnect(1);
		bt_set_scan_mode(false,true);
		bsp_set_led_mode(LED_POWER_OFF);
	}
}


AT(.text.func.bt)
void func_bt_change_vol(u8 dir)
{
 	u32 tmp_ticks;
	u32 max_time=350;
	if(sys_cb.vol==0||sys_cb.vol == VOL_MAX)
	{
		tmp_ticks= tick_get();
		if(tmp_ticks>key_ticks)
		{
			//printf("tmp_ticks:%d->key_ticks:%d\n",tmp_ticks,key_ticks);
			if((tmp_ticks-key_ticks)<max_time)
			{
				return;
			}
		}
	}
	if(dir%2)
	{
		bsp_set_volume(bsp_volume_inc(sys_cb.vol));
		func_set_vol_callback(1);
        bsp_bt_vol_change();
		delay_5ms(4);
		//printf("vol add!!\n");
		if (sys_cb.vol == VOL_MAX)
		{
				key_ticks=tick_get();
				amp_speaker_unmute();
				maxvol_tone_play();
				if(f_bt.disp_status != BT_STA_PLAYING)
				{
					amp_speaker_mute();
				}
        }
		else
		{
			key_ticks=0;
		}
	}
	else
	{
		bsp_set_volume(bsp_volume_dec(sys_cb.vol));
        func_set_vol_callback(0);
        bsp_bt_vol_change();
		delay_5ms(4);
		//printf("vol sub!!\n");
		if (sys_cb.vol == 0)
		{
			bt_audio_bypass();
			amp_speaker_unmute();
			bsp_change_volume(VOL_MAX);
			maxvol_tone_play();
			if(f_bt.disp_status != BT_STA_PLAYING)
			{
				amp_speaker_mute();
			}
			bsp_change_volume(0);
			bt_audio_enable();
			key_ticks=tick_get();
        }
		else
		{
			key_ticks=0;
		}
	}
	sys_cb.vol_sync_to_remote=0;
	f_bt.sync_vol_cnt=0;
	printf("cur vol:%d\n",sys_cb.vol);
}
AT(.text.func.bt)
void func_bt_reset_timeout(void)
{
	if(f_bt.bt_status==0)
	{
		f_bt.idle_cnt=0;
	}

}
void func_check_reconnect(void)
{
	if(need_reconnect_flag)
	{
		if(f_bt.disp_status>=BT_STA_CONNECTED)
		{
			need_reconnect_flag=0;
			reconnect_cnt=0;
			return;
		}
		reconnect_cnt++;
		if(reconnect_cnt>4)
		{
			need_reconnect_flag=0;
			reconnect_cnt=0;
			func_set_reconnect_device();
		}
	}
}
AT(.text.func.bt)
void bt_reset_light_idle_timeout(void)
{
	sys_cb.light_idle_cnt=0;
}
AT(.text.func.bt)
void bt_check_light_status(void)
{
	if(bsp_get_light_mode()!=0)
	{
		sys_cb.light_idle_cnt++;
		printf("light time out cnt:%d\n",sys_cb.light_idle_cnt);
		if(sys_cb.light_idle_cnt>=BT_LIGHT_IDLE_TIMEOUT)
		{
			bsp_set_light_off();
			sys_cb.light_idle_cnt=0;
		}
	}
}

AT(.text.func.bt)
void check_bt_ilde_timeout(void)
{
	//func_check_reconnect();
	bt_check_light_status();
	if(f_bt.disp_status>=BT_STA_CONNECTED)
	{
		if(sys_cb.vol_sync_to_remote)
		{
			f_bt.sync_vol_cnt++;
			if(f_bt.sync_vol_cnt>=4)
			{
				sys_cb.vol_sync_to_remote=0;
				f_bt.sync_vol_cnt=0;
				if(sys_cb.sco_start)
				{
					bt_ctrl_msg(BT_CTL_HFP_SPK_GAIN);
            		bsp_change_volume(sys_cb.hfp_vol * sys_cb.hfp2sys_mul);
				}
				else
				{
					bsp_bt_vol_change();
				}

			}
		}
	}
	//printf("disp_status:%d\n",f_bt.disp_status);
	if(f_bt.disp_status>=BT_STA_CONNECTED)
	{
		return;
	}
	if(f_bt.bt_status==0)
	{
		return;
	}
	f_bt.idle_cnt++;
	if(f_bt.idle_cnt!=0)
	{
		printf("idle cnt:%d\n",f_bt.idle_cnt);
	}
	//printf("disp_status:%d\n",f_bt.disp_status);
	//printf("out_f_range:%d\n",f_bt.out_f_range);
	#if 1
	if(f_bt.out_f_range&&(f_bt.disp_status<BT_STA_CONNECTED)&&f_bt.idle_cnt<BT_OUTOFRANGE_TIMEOUT)
	{
		#if 1
		if(f_bt.idle_cnt%10==0)
		{
			bt_disconnect(1);
			bt_abort_reconnect();
			delay_5ms(100);
			bt_connect(10);
		}
		#endif
		//bt_set_scan_mode(true,true);
				
		//delay_5ms(20);
		
	}
	if(f_bt.out_f_range&&(f_bt.disp_status<BT_STA_CONNECTED)&&(f_bt.idle_cnt>(BT_OUTOFRANGE_TIMEOUT+6)))
	{
		f_bt.out_f_range=0;
		f_bt.bt_status=0;
		bt_abort_reconnect();
		bt_disconnect(1);
		bt_set_scan_mode(false,true);
		bsp_set_led_mode(LED_POWER_OFF);
	}
	#endif
	if(f_bt.out_f_range&&f_bt.idle_cnt==BT_OUTOFRANGE_TIMEOUT)
	{
		printf("dis display!!\n");
		f_bt.out_f_range=0;
		f_bt.bt_status=0;
		bt_set_scan_mode(false,true);
		bsp_set_led_mode(LED_POWER_OFF);
	}
	else if(f_bt.idle_cnt==BT_PAIR_TIMEOUT)
	{
		//cfg_bt_scan_ctrl_mode = 1;
		bt_set_scan_mode(false,true);
		if(f_bt.bt_status==1)
		{
			f_bt.idle_cnt=0;			
			func_mp3_res_play(RES_BUF_EN_TIMEOUT_MP3, RES_LEN_EN_TIMEOUT_MP3);
			bsp_set_led_mode(LED_BT_PAIR_FAIL);
			f_bt.bt_status=0;
			reconnect_order=0;
			//bt_connect(BT_POWER_UP_RECONNECT_TIMES);	
			//func_set_reconnect_device();
		}
		else if(f_bt.bt_status==2)
		{
			bt_set_scan_mode(false,true);
			f_bt.bt_status=0;
			f_bt.idle_cnt=0;
			bsp_set_led_mode(LED_POWER_OFF);
			//f_bt.bt_status=0;
			//f_bt.idle_cnt=0;
		}
		else
		{
			f_bt.bt_status=0;
			f_bt.idle_cnt=0;
		}
		
	}
	if(f_bt.idle_cnt>=BT_IDLE_TIMEOUT)
	{
		//func_cb.sta=FUNC_IDLE;
		bsp_set_led_mode(LED_POWER_OFF);
		f_bt.idle_cnt=0;
		f_bt.bt_status=0;
	}
}
 AT(.text.func.bt)
void func_sco_play_ctl(u8 onoff)
{
	if(onoff)
	{
		sys_cb.sco_start=1;
		sys_cb.vol_sync_to_remote=1;
		amp_speaker_unmute();

	}
	else
	{
		sys_cb.sco_start=0;
		amp_speaker_unmute();
		bsp_change_volume(sys_cb.vol);
		//amp_speaker_mute();
	}
}

 AT(.text.func.bt)
 void func_play_sdk_version(void)
{
	func_mp3_res_play(RES_BUF_EN_SDK_VERSION_MP3, RES_LEN_EN_SDK_VERSION_MP3);
}

 AT(.text.func.bt)
 u8 check_power_key(void)
 {
	 u8 key_cnt=0;
	 u16 msg;
	 while (1)
	 {
		 WDT_CLR();
		 delay_ms(20);
		 msg = msg_dequeue();
		 //printf("msg:0x%x\n",msg);
		 if(msg==KL_POWER||msg==KH_POWER)
		 {
			 key_cnt=10;
			 break;
		 }
		 key_cnt++;
		 if(key_cnt>6)
		 {
			 break;
		 }
	 }
	 if(key_cnt>=10)
	 {
		 return 0;
	 }
	 else
	 {
		 return 1;
	 }
 }


 void func_bt_enter(void)
{
    func_cb.mp3_res_play = func_bt_mp3_res_play;
    func_bt_enter_display();
    led_bt_init();
    dis_auto_pwroff();
    func_bt_init();
	amp_speaker_unmute();
	bsp_set_led_mode(LED_POWER_ON);
	mp3_res_play(RES_BUF_EN_POWERON_MP3, RES_LEN_EN_POWERON_MP3);
	mic_bias_trim();
#if WARNING_FUNC_BT
    mp3_res_play(RES_BUF_BT_MODE_MP3, RES_LEN_BT_MODE_MP3);
#endif // WARNING_FUNC_BT

#if WARNING_BT_WAIT_CONNECT
    mp3_res_play(RES_BUF_WAIT4CONN_MP3, RES_LEN_WAIT4CONN_MP3);
#endif // WARNING_BT_WAIT_CONNECT
	#if 0
	if(check_power_key()==0)
	{
		printf("key long!!\n");
		long_wakeup=1;
	}
	#endif
	#if 1
	{
		u8 i;
		u8 temp_buf[12];
		printf("get bt addr:\n");
		memset(bt_device_addr,0x0,6);
		bt_device_num=0;
		reconnect_order=0;
		for(i=0;i<2;i++)
		{
			if(bt_nor_get_link_info_addr(bt_device_addr,i))
			{
				bt_device_num++;
				print_r(bt_device_addr,6);
				printf("\n");
			}
		}
	}
	#endif
	if(bt_device_num==0)
	{
		f_bt.bt_status=1;
		bt_set_scan_mode(true,true);
		bsp_set_led_mode(LED_BT_PAIR);
		mp3_res_play(RES_BUF_EN_PAIRING_MP3, RES_LEN_EN_PAIRING_MP3);
	}
	else
	{
		
		#if 0
		u8 temp_buf[12];
		f_bt.bt_status=2;

		if(bt_device_num==2)
		{
			//printf("addr is OK\n");
			//print_r(temp_buf,6);
			bt_nor_get_link_info_addr(addr_buf,0);
			bt_get_connect_addr(temp_buf);
			bt_connect_address();
		}
    	else
    	{
    		//printf("addr err!\n");
			bt_connect(BT_POWER_UP_RECONNECT_TIMES);
    	}
		#endif
		f_bt.bt_status=2;
		bt_set_scan_mode(false,true);
		if(bt_device_num==2)
		{
			need_reconnect_flag=2;
			//bt_connect(2);
			//func_set_reconnect_device();
			reconnect_order=0;
			bt_connect(5);
		}
		else
		{
			bt_connect(BT_POWER_UP_RECONNECT_TIMES);	
		}
		//	
		//func_set_reconnect_device();
		//bt_connect(BT_POWER_UP_RECONNECT_TIMES);
		
		bsp_set_led_mode(LED_BT_RECONNECT);
	}
	if(check_power_key()==0)
	{
		printf("key long!!\n");
		long_wakeup=1;
	}
	f_bt.idle_cnt=0;
    f_bt.disp_status = 0xfe;
    f_bt.rec_pause = 0;
    f_bt.pp_2_unmute = 0;
    sys_cb.key2unmute_cnt = 0;
	sys_cb.vol_sync_to_remote=0;
	f_bt.sync_vol_cnt=0;
    bt_redial_init();
    bt_audio_enable();
#if DAC_DNR_EN
    dac_dnr_set_sta(1);
    sys_cb.dnr_sta = 1;
#endif

#if SYS_KARAOK_EN && UDE_MIC_KARAOK_EN
    bsp_karaok_init(AUDIO_PATH_KARAOK, FUNC_BT);
    dac_fade_in();
#endif

#if BT_PWRKEY_5S_DISCOVER_EN
    if(bsp_bt_pwrkey5s_check()) {
        f_bt.need_pairing = 0;  //已经播报了
        func_bt_disp_status();
#if WARNING_BT_PAIR
        func_mp3_res_play(RES_BUF_PAIRING_MP3, RES_LEN_PAIRING_MP3);
#endif
    } else {
        func_bt_disp_status();
#if WARNING_BT_PAIR
        if (xcfg_cb.warning_bt_pair && !xcfg_cb.bt_tws_en) {
            func_mp3_res_play(RES_BUF_PAIRING_MP3, RES_LEN_PAIRING_MP3);
        }
#endif // WARNING_BT_PAIR
    }
#endif

#if BT_REC_EN
    bt_music_rec_init();
#endif // BT_REC_EN

#if BT_TWS_EN
    if(xcfg_cb.bt_tws_pair_mode > 1) {
        bt_tws_set_scan(1, 1);
    }
#endif

#if AUX_AUTO_SWITCH_BT
    aux_channel_init();
#endif // AUX_AUTO_SWITCH_BT

#if UART_S_UPDATE
    uart_upd_init(UART_UPD_PORT_SEL,UART_UPD_BAUD,SYS_CLK_SEL);
    uart_upd_isr_init();
#endif // UART_S_UPDATE
}

AT(.text.func.bt)
void func_bt_exit(void)
{
#if SYS_KARAOK_EN && UDE_MIC_KARAOK_EN
    bsp_karaok_exit(AUDIO_PATH_KARAOK);
#endif

#if BT_REC_EN
    sfunc_record_stop();
#endif // BT_REC_EN
    dac_fade_out();
#if DAC_DNR_EN
    dac_dnr_set_sta(0);
    sys_cb.dnr_sta = 0;
#endif
#if BT_PWRKEY_5S_DISCOVER_EN
    bsp_bt_pwrkey5s_clr();
#endif
    func_bt_exit_display();
    bt_audio_bypass();
#if BT_TWS_EN
    dac_mono_init(1, 0);
#endif
#if !BT_BACKSTAGE_EN
    bt_disconnect(1);
    bt_off();
    f_bt.bt_is_inited = 0;
#else
    if (bt_get_status() == BT_STA_PLAYING && !bt_is_testmode()) {        //蓝牙退出停掉音乐
        delay_5ms(10);
        if(bt_get_status() == BT_STA_PLAYING) {     //再次确认play状态
        #if BT_SUPPORT_IOS_FAST_STATUS && !BT_BACKSTAGE_PLAY_DETECT_EN //加快蓝牙后台的退出
            u32 timeout = 20;
        #else
            u32 timeout = 850; //8.5s
        #endif
            bt_music_pause();
            while (bt_get_status() == BT_STA_PLAYING && timeout > 0) {
                timeout--;
                delay_5ms(2);
            }
        }
    }
#endif
	bsp_set_led_mode(LED_POWER_OFF);
	func_mp3_res_play(RES_BUF_EN_POWEROFF_MP3, RES_LEN_EN_POWEROFF_MP3);
	amp_speaker_mute();
	if(bsp_get_light_mode()!=0)
	{
		func_cb.sta=FUNC_IDLE;
	}
    f_bt.rec_pause = 0;
    f_bt.pp_2_unmute = 0;
    sys_cb.key2unmute_cnt = 0;
	param_sync();
    func_cb.last = FUNC_BT;

#if AUX_AUTO_SWITCH_BT
    audio_path_exit(AUDIO_PATH_AUX);
#endif // AUX_AUTO_SWITCH_BT
}


AT(.text.func.bt)
void func_bt(void)
{
    printf("%s\n", __func__);

    func_bt_enter();

    while (func_cb.sta == FUNC_BT) {
        func_bt_process();
        func_bt_message(msg_dequeue());
        func_bt_display();
		//func_restore_vol_set();
    }

    func_bt_exit();

}

#if FUNC_FCC_MODE_EN
AT(.rodata.bt.cbt)
const u8 led_bt_cbt_tbl[] = {
    0xff, 0x00, 0x02, 0x00, 0xff, 0x00, 0x02, 0x00, 0xff, 0x00, 0x02, 0x00, 0xff, 0x00, 0x02, 0x00,
};
//FCC 测试模式
AT(.text.func.bt)
void func_bt_fcc(void)
{
    printf("%s\n", __func__);
    sys_cb.pwroff_delay = sys_cb.pwroff_time = -1;                          //关闭未连接自动关机
    sys_cb.sleep_time = -1;                                                 //不进siff mode
    sys_cb.sleep_en = 0;
    memcpy(&xcfg_cb.led_btinit, led_bt_cbt_tbl, sizeof(led_bt_cbt_tbl));    //红灯常亮
//    if (xcfg_cb.bb_cbt_test_addr_fixed_en) {
//        xcfg_cb.bt_addr_config_en = 1;
//        memset(xcfg_cb.bt_addr, 0x68, 6);                                   //固定蓝牙地址
//    }
    cfg_bt_work_mode = MODE_FCC_TEST;

    printf("----->a\n");
    func_bt_enter();
    printf("----->b\n");
    func_aux_start();
    printf("----->c\n");
    while (func_cb.sta == FUNC_BT_FCC) {
        func_bt_process();
        func_bt_message(msg_dequeue());
    }
    func_bt_exit();
    cfg_bt_work_mode = 0;
    func_cb.last = FUNC_BT_FCC;
}
#endif // FUNC_FCC_MODE_EN

#endif //FUNC_BT_EN
